package com.ruoyi.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.project.setting.utils.DataScopeUtils;
import com.ruoyi.common.annotation.SysLog;
import com.ruoyi.common.constant.CommonConstants;
import com.ruoyi.common.enums.BaseStatusEnum;
import com.ruoyi.common.enums.BusinessTypeEnum;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.system.entity.SysDept;
import com.ruoyi.project.system.entity.SysTenant;
import com.ruoyi.project.system.entity.SysUser;
import com.ruoyi.project.system.service.ISysDeptService;
import com.ruoyi.project.system.service.ISysUserService;
import com.ruoyi.project.system.service.SysTenantService;
import lombok.AllArgsConstructor;
import net.dreamlu.mica.core.result.R;
import net.dreamlu.mica.core.utils.$;
import net.dreamlu.mica.core.utils.StringPool;
import net.dreamlu.mica.core.validation.CreateGroup;
import net.dreamlu.mica.core.validation.UpdateGroup;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门 控制层
 *
 * @author dy
 */
@RestController
@RequestMapping("/system/dept")
@AllArgsConstructor
public class SysDeptController extends BaseController {
    
    private final SysTenantService sysTenantService;

    private final ISysDeptService sysDeptService;

    private final ISysUserService sysUserService;

    /**
     * 树形部门列表
     */
    @GetMapping("/list")
    public R list(SysDept sysDept) {
        List<SysDept> deptList = sysDeptService.list(new LambdaQueryWrapper<SysDept>()
                .like($.isNotBlank(sysDept.getDeptName()), SysDept::getDeptName, sysDept.getDeptName())
                .eq($.isNotNull(sysDept.getStatus()), SysDept::getStatus, sysDept.getStatus())
                .apply(DataScopeUtils.getDataScopeSql("sys_dept", "id", "create_by"), 1));
        return success(deptList);
    }

    /**
     * 详情
     */
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping("/detail")
    public R<SysDept> detail(Long id) {
        SysDept sysDept = sysDeptService.getById(id);
        return success(sysDept);
    }

    /**
     * 新增
     */
    @SysLog(title = "部门管理", businessType = BusinessTypeEnum.INSERT)
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @PostMapping("/add")
    public R add(@Validated(value = {CreateGroup.class}) @RequestBody SysDept sysDept) {
        setSysDeptAncestors(sysDept);
        sysDept.setCreateDept(sysDept.getId());
        boolean deptSaveStatus = sysDeptService.saveIgnore(sysDept);
        if (sysDept.getParentId() == 0) {
            SysTenant sysTenant = new SysTenant();
            sysTenant.setTenantId(sysDept.getParentId());
            sysTenant.setTenantName(sysDept.getDeptName());
            deptSaveStatus = sysTenantService.save(sysTenant);
        }
        return status(deptSaveStatus);
    }

    /**
     * 修改
     */
    @SysLog(title = "部门管理", businessType = BusinessTypeEnum.UPDATE)
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @PutMapping("/update")
    public R update(@Validated(value = {UpdateGroup.class}) @RequestBody SysDept sysDept) {
        if (sysDept.getId().equals(sysDept.getParentId())) {
            return fail("修改部门'" + sysDept.getDeptName() + "'失败，上级部门不能是自己");
        }
        setSysDeptAncestors(sysDept);

        // childdept祖级列表
        List<SysDept> childDeptList = sysDeptService.list(new LambdaQueryWrapper<SysDept>()
                .apply(CommonConstants.SQL_FIND_IN_SET, sysDept.getId()));
        SysDept self = sysDeptService.getById(sysDept.getId());
        for (SysDept v : childDeptList) {
            if (BaseStatusEnum.DB_STATUS_DISABLE.getStatus().equals(sysDept.getStatus())) {
                if (BaseStatusEnum.DB_STATUS_NORMAL.getStatus().equals(v.getStatus())) {
                    return fail("该部门包含未停用的子部门！");
                }
            }
            // 修改了上级
            if (!self.getParentId().equals(sysDept.getParentId())) {
                v.setAncestors(sysDept.getAncestors() + StringPool.COMMA + sysDept.getId());
                sysDeptService.updateById(v);
            }
        }

        return status(sysDeptService.updateById(sysDept));
    }

    /**
     * 删除
     */
    @SysLog(title = "部门管理", businessType = BusinessTypeEnum.DELETE)
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable Long id) {
        int deptCount = sysDeptService.count(new LambdaQueryWrapper<SysDept>()
                .like(SysDept::getAncestors, id));
        if (deptCount > 0) {
            return fail("存在下级部门,不允许删除");
        }
        int userCount = sysUserService.count(new LambdaQueryWrapper<SysUser>().eq(SysUser::getCreateDept, id));
        if (userCount > 0) {
            return fail("部门存在用户,不允许删除");
        }
        SysDept sysDept = new SysDept();
        sysDept.setId(id);
        boolean result = sysDeptService.updateById(sysDept) && sysDeptService.removeById(id);
        return status(result);
    }

    private void setSysDeptAncestors(SysDept sysDept) {
        // sysdept祖级列表
        SysDept parentDept = sysDeptService.getById(sysDept.getParentId());
        if ($.isNotNull(parentDept) && $.isNotBlank(parentDept.getAncestors())) {
            sysDept.setAncestors(parentDept.getAncestors() + StringPool.COMMA + parentDept.getId());
        } else {
            sysDept.setAncestors("0");
        }
    }
}
